<?php
namespace App\Repositories;


use App\Models\Area;
use App\Models\Cimo\UserNeed;
use App\Models\Cimo\UserResume;
use App\Models\Cimo\UserResumeEducational;
use App\Models\Cimo\UserResumeExperience;
use App\Models\Cimo\UserResumeProject;
use App\Models\Cimo\ExamHistory;
use App\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;


class UserResumeRepository
{
    use BaseRepository;
    /**
     * @var gzxz  工作性质字典
     * 工作性质  0 全职， 1 兼职 ， 2 实习 ，默认0 全职
     */
    protected $gzxz = array();
    /**
     * @var salary 薪资 字典
     * 薪资 0:2k以下；1：2k-5K；2：5k-10k; 3:10k-15k; 4:15k-25k; 5:25k-50k; 6:50k以上 默认0
     */
    protected $salary = array();
    /**
     * @var degree 学历
     * 0：大专；1本科；2:硕士；3：博士；4其它； 默认0
     */
    protected $degree = array();
    /**
     * @var gznx 工作年限
     * 工作年限 0 应届毕业生 1：1年 ； 2：2年 。。。。10：年  ； >10 为10年以上
     */
    protected $gznx = array();
    private $model;
    private $userNeed;
    private $userResumeEdu;
    private $userResumeExp;
    private $userResumeProd;
    private $userResumeProj;
    private $examHistory;
    private $error_code = 0;
    private $error_msg = '';

    public function __construct(UserResume $userResume, UserNeed $userNeed, UserResumeEducationals $userResumeEdu,
                                UserResumeExperiences $userResumeExp, UserResumeProducts $userResumeProd,
                                UserResumeProjestRepository $userResumeProj,
                                ExamHistory $examHistory)
    {
        $this->model = $userResume;
        $this->userNeed = $userNeed;
        $this->userResumeEdu = $userResumeEdu;
        $this->userResumeExp = $userResumeExp;
        $this->userResumeProd = $userResumeProd;
        $this->userResumeProj = $userResumeProj;
        $this->examHistory = $examHistory;

        $this->salary = array(0=>'2k以下',1=>'2k~5k',2=>'5k~10k',3=>'10k~15k',4=>'15k~25k',5=>'25k~50k',6=>'50k以上',7=>'面议');
        $this->gznx = array(0=>'应届毕业生',1=>'1年以下',2=>'1-3年',3=>'3-5年',4=>'5-10年',5=>'10年以上',100=>'不限');
        $this->degree = array(0=>'大专',1=>'本科',2=>'硕士',3=>'博士',4=>'其他',100=>'不限');
        $this->gzxz = array(0=>'全职',1=>'兼职',2=>'实习',100=>'不限');
    }

    /**
     * 查看用户简历
     * @param int $id 用户编号
     */
    public function show($id)
    {
        $resume = $this->model->where('id',$id)->first();
        if(empty($resume))
        {
            return $this->formatJson('error','请求出错！');
        }else{
            $area = Area::where('area_id','=',$resume->city)->first();
            $resume->cityname = empty($area)?'':$area->title;
            $resume->logo = userlogo($resume->id, 'middle');
            $birth_year = new Carbon($resume->user->birth_year);
            $now = Carbon::now();
            $resume->age = $birth_year->diff($now)->y;
            $resume->sex = $resume->sex = 0?'女':'男';
            $resume->gznx = $this->gznx[$resume->gznx];
            $resume->degree = $this->degree[$resume->highest_degree];
            $resume->gzxzs = $this->gzxz;
            $resume->gznxs = $this->gznx;
            $resume->degrees = $this->degree;
            $resume->salarys = $this->salary;
            $resume->experiences = $resume->experiences;
            $resume->educationals = $resume->educationals;
            $resume->projects = $resume->projects;
            $resume->needs = $this->userNeed->where('resume_id',$resume->id)->first();
            $expect_area = Area::where('area_id','=',$resume->needs->city)->first();
            $resume->expect_cityname = empty($expect_area)?'':$expect_area->title;
        }

        return $resume;
    }

    /**
     * 更新
     * @param int $id
     * @param $input
     * @return \App\Models\AccountEvents
     */
    public function update($id, $input)
    {
        $model = $this->model->find($id);

        return $this->savePost($model, $input);
    }
    
    /**
     * save.
     *
     * @param Request $input 输入
     */
    public function savePost($events, $input)
    {
        $events->fill($input);
        $events->save();

        return $events;
    }


    public function getResume($resume_id)
    {
        return $this->model->withTrashed()->find($resume_id);
    }

    /**
     * 获取用户简历列表
     *
         * @param int $uid
     * @param int $pageSize
     */
    public function lists($uid,$pageSize)
    {
        return $this->model->where(['user_id' => $uid])->orderBy('id', 'DESC')->paginate($pageSize);
    }

    public function getUserId($resume_id)
    {
        return $this->model->where('id',$resume_id)->value('user_id');
    }

    /**
     * 查看简历
     * @param integer $uid  用户编号
     * @param integer $resume_id  简历编号
     * @param bool $addViews  是否自增+1简历访问量
     * @return bool|object
     */
    public function viewResume($resume_id, $addViews = FALSE,$need_id=0)
    {
        if(empty($resume_id)) {
            $this->error_code = -1;
            $this->error_msg = '简历不存在';
            return FALSE;
        }
        $resume = $this->getById($resume_id,'user');

        $resume->tags = $resume->tags;

        if (count($resume->user) <= 0) {
            $this->error_code = -1;
            $this->error_msg = '用户不存在';
            return FALSE;
        }

        if (!$resume) {
            $this->error_code = -1;
            $this->error_msg = '简历不存在';
            return FALSE;
        }

        // 工作经历
        $resume->experiences = UserResumeExperience::where('resume_id', '=', $resume_id)->get();
        //表字段时间类型不统一带来的烦恼！:)
        foreach ($resume->experiences as &$v) {
            $v['start_at'] = date('Y/m', $v['start_at']);
            $v['end_at'] = date('Y/m', $v['end_at']);
        }
        unset($v);
        //教育经历
        $resume->educationals = UserResumeEducational::where('resume_id', '=', $resume_id)->get();
        foreach ($resume->educationals as &$v) {
            $v['graduated_at'] = date('Y', $v['graduated_at']);
        }
        unset($v);
        //项目经验
        $resume->projects = UserResumeProject::where('resume_id', '=', $resume_id)->get();
        foreach ($resume->projects as &$v) {
            $v['start_at'] = date('Y/m', $v['start_at']);
            $v['end_at'] = date('Y/m', $v['end_at']);
        }
        unset($v);
        //工作期望/需求
        if($need_id){
            $resume->needs = $this->userNeed->withTrashed()->find($need_id);
            if ($resume->needs) {
                $r = Area::select('title')->where('area_id', '=', $resume->needs->city)->first();
                $resume->needs->cityname = $r ? $r->title : '';
            }

            
            if(count($resume->needs)){
                $skill_exam = $this->examHistory->find($resume->needs->skill_exam);
            }
    
            $resume->skill_exam_score = is_null($skill_exam)?null:$skill_exam->score;
            
        }
        $resume->logo = userlogo($resume->user->id, 'middle');
        $resume->sex = $resume->user->sex = 0 ? '女' : '男';
        $resume->age = user_age($resume->user->birth_year, $resume->user->birth_month);
        $resume->tags = $resume->tags;
        if($resume->province > 0) {
            $resume->province = Area::where('area_id',$resume->province)->value('title');
            $resume->city = Area::where('area_id',$resume->city)->value('title');
        } else {
            $resume->province = '';
            $resume->city ='';
        }

        //简历查看量+1
        if ($addViews)
        {
            $this->increment('views', 1, $resume->id);
        }
        $this->model->where('id', $resume_id)->increment('views');
       // $resume->logo = userlogo($resume->user->id, 'middle');
        return $resume;
    }

    /**
     * 根据主键+用户编号查找，校验用户权限
     * @param $id
     * @param $uid
     * @return mixed
     */
    public function findWithUid($id, $uid)
    {
        return $this->model->where('user_resumes.user_id', '=', $uid)->find($id);
    }

    /**
     * 错误代码
     * @return int
     */
    public function getErrorCode()
    {
        return $this->error_code;
    }

    /**
     * 错误消息
     * @return string
     */
    public function getErrorMsg()
    {
        return $this->error_msg;
    }

    /**
     * 复制简历
     * @param integer $resume_id  简历ID
     * @param integer $uid 用户ID
     * @param array $attr  附加属性 ['name'=>'新简历名称', 'exp' => 1/0, 'edu' => 1/0, 'proj'=> 1/0]
     * @return bool
     */
    public function copyBuilder($resume_id, $uid, array $attr)
    {
        $d = $this->model->find($resume_id);
        //基础信息
        $input = $d->toArray();
        $input['user_id'] = $uid;
        $input['name'] = $attr['name'];
        $input['views'] = 0;
        DB::beginTransaction();
        try {
            $userResume = $this->store($input);
            if($userResume){
                //工作经验
                if (isset($attr['exp'])) {
                    $rows = $d->experience->toArray();
                    foreach ($rows as &$v) {
                        $v['resume_id'] = $userResume->id;
                        $this->userResumeExp->store($v);
                    }
                    unset($v);
                }
                //教育经历
                if (isset($attr['edu'])) {
                    $rows = $d->educational->toArray();
                    foreach ($rows as &$v) {
                        $v['resume_id'] = $userResume->id;
                        $this->userResumeEdu->store($v);
                    }
                    unset($v);
                }
                //项目经验
                if (isset($attr['proj'])) {
                    $rows = $d->project->toArray();
                    foreach ($rows as &$v) {
                        $v['resume_id'] = $userResume->id;
                        $this->userResumeProj->store($v);
                    }
                    unset($v);
                }
            }
            DB::commit();
        }catch (\PDOException $e){
            Log::info(['用户简历复制异常'=>$e->getMessage()]);
            DB::rollBack();
            return FALSE;
        }
        return TRUE;
    }

    /**
     * store.
     *
     * @param array $input
     */
    public function store($input)
    {
        return $this->savePost($this->model, $input);
    }
}

